package com.ygt.conf;

import com.ygt.servlet.HttpServlet;
import com.ygt.util.SearchClassUtil;
import com.ygt.webServlet.WebServlet;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author ygt
 * @Date 2022/11/17 15:07
 * @Version 1.0
 */
public class ServletConfigMapping {

    //定义servlet容器
    public static Map<String,Class<HttpServlet>> classMap = new HashMap<>();

    //将每一个自定义servlet类的信息放入ServletConfig中
    private static List<ServletConfig> configs = new ArrayList<>();


    static {
        //获取用户自定义的servlet全路径名
        List<String> classPaths = SearchClassUtil.searchClass();
        for (String classPath:classPaths) {
            try {
                getMessage(classPath);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    //使用反射获取注解信息
    public static void getMessage(String classPath) throws Exception {
        Class clazz = Class.forName(classPath);
        //获取注解信息
        WebServlet webServlet = (WebServlet) clazz.getDeclaredAnnotation(WebServlet.class);

        //需要将解析的信息加载到configs集合当中（保证url和类对象是相同的）
        configs.add(new ServletConfig(webServlet.urlMapping(), classPath));
    }


    //将url和类对象放入到servlet容器
    public static void initServlet() throws ClassNotFoundException {
        for (ServletConfig config:configs) {
            classMap.put(config.getUrlMapping(), (Class<HttpServlet>) Class.forName(config.getClassPath()));
        }
    }


}
